import ArticleItem from '@/components/ArticleItem';
import { useAppSelector } from '@/store';
import {
  getArtilesByIdAction,
  updateArtilesByIdAction,
} from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useDispatch } from 'react-redux';

// type Props = {
//   channel_id: number;
// };

export default function ArticleList() {
  const dispatch = useDispatch();
  // 取数据
  const { currentId } = useAppSelector((state) => state.channel);
  const { articleList } = useAppSelector((state) => state.article);
  // 1. 取出后台返回的时间戳
  const pre_timestamp = articleList[currentId]?.pre_timestamp;
  console.log(
    ' articleList ----->  ',
    articleList,
    currentId,
    articleList[currentId]
  );
  const list = articleList[currentId]?.results || [];
  const loadMore = async () => {
    // 使用新的时间戳，请求数据
    await dispatch(
      updateArtilesByIdAction({
        channel_id: currentId,
        timestamp: pre_timestamp,
      })
    );
    console.log(36, pre_timestamp);
  };
  // 2.onRefresh触发下拉
  const handleRefresh = async () => {
    // 3. 使用getArtilesByIdAction请求数据
    await dispatch(getArtilesByIdAction({ channel_id: currentId }));
  };
  return (
    <PullToRefresh onRefresh={handleRefresh}>
      <div>
        {/* 2. 列表渲染ArticleItem */}
        {list.map((item) => {
          return <ArticleItem data={item as any} key={item.art_id} />;
        })}
        {/* 💥下方控制数据为空时，不去显示无限滚动组件 */}
        {!!list.length && (
          <InfiniteScroll loadMore={loadMore} hasMore={!!pre_timestamp} />
        )}
      </div>
    </PullToRefresh>
  );
}
